package com.itheima.Vue.web.manager.service;

import com.itheima.Vue.web.manager.dao.ContactDao;
import com.itheima.Vue.web.manager.pojo.Contact;
import com.itheima.Vue.web.manager.pojo.PageBean;
import com.itheima.Vue.web.manager.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;

/*
        业务处理
 */
public class ContactService {
    public PageBean pageQuery(String pageStr, String countStr, HashMap<String, String> conditionMap) {
        //1. 前端参数处理
        /*
         *  先默认page=1,count=5 -> 代码健壮性
         *  前端给了,就用前端设置的参数
         * */

        int page = 1;
        int count = 5;




        if (pageStr!= null && !pageStr.equals("")){
            page = Integer.parseInt(pageStr);
        }
        if (countStr!= null && !countStr.equals("")){
            count = Integer.parseInt(countStr);
        }

        //2.数据库查寻
        SqlSession sqlSession = SqlSessionUtil.getSession(true);
        ContactDao dao = sqlSession.getMapper(ContactDao.class);
        int index = (page-1) * count;
        //2.1联系人分页查寻
        List<Contact> list = dao.findListByPage(index,count,conditionMap);
        //2.2 联系人总数
        int sum = dao.findContactSum(conditionMap);


        sqlSession.close();

        //3.封装PageBean
        PageBean bean = PageBean.getBean(page, count, list, sum);
        return bean;

    }

    public void save(Contact contact) {
        SqlSession session = SqlSessionUtil.openSession();
        ContactDao mapper = session.getMapper(ContactDao.class);
        mapper.addContact(contact);


        session.close();


    }

    public void updateContact(Contact contact) {
        SqlSession session = SqlSessionUtil.openSession();
        ContactDao mapper = session.getMapper(ContactDao.class);
        mapper.updateContact(contact);
    }


    public Contact getContactById(String idStr) {
        int id = Integer.parseInt(idStr);
        SqlSession session = SqlSessionUtil.openSession();
        ContactDao mapper = session.getMapper(ContactDao.class);
        Contact Contact = mapper.getContactById(id);
        session.close();
        return Contact;
    }

    public void deleteContact(String idStr) {
        int id = Integer.parseInt(idStr);
        SqlSession session = SqlSessionUtil.openSession();
        ContactDao mapper = session.getMapper(ContactDao.class);
        mapper.deleteContactById(id);
        session.close();

    }
}
